/*
 * Copyright (c) jiucheng.org
 */
package org.jiucheng.template.grammar;

import java.util.Map;

import org.jiucheng.template.util.Objs;
import org.jiucheng.template.util.Rgxs;

/**
 * 
 * @author jiucheng
 *
 */
public class Print implements Grammar {

    public Print(String[] prints) {
        init(prints);
    }

    private void init(String[] prints) {
        if (prints != null && prints.length > 0) {
            this.prints = new String[prints.length];
            args = new String[prints.length][];
            for (int i = 0; i < prints.length; i++) {
                pnt(i, prints[i]);
            }
        }
    }

    private void pnt(int i, String print) {
        StringBuilder sb = new StringBuilder();
        args[i] = Rgxs.complier(print, sb);
        prints[i] = sb.toString();
    }

    private String[] prints;
    private String[][] args;

    public void exec(Map<String, Object> context, StringBuilder sb) {
        if (prints != null) {
            for (int i = 0; i < prints.length; i++) {
                sb.append(getPrint(context, prints[i], args != null ? args[i] : null));
            }
        }
    }

    protected String getPrint(Map<String, Object> context, String print, String[] arg) {
        if (arg == null) {
            return print;
        }
        Object obj;
        for (int i = 0; i < arg.length; i++) {
            obj = Objs.get(context, arg[i]);
            print = print.replace("{" + i + "}", obj != null ? obj.toString() : "");
        }
        return print;
    }
}
